package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysTenant;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.bo.SysTenantAddBo;
import com.ruoyi.system.domain.bo.SysTenantEditBo;
import com.ruoyi.system.domain.bo.SysTenantQueryBo;
import com.ruoyi.system.domain.vo.SysTenantVo;
import com.ruoyi.system.mapper.SysTenantMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 租户Service业务层处理
 *
 * @author lingdeng
 * @date 2021-07-24
 */
@Service
public class SysTenantServiceImpl extends ServicePlusImpl<SysTenantMapper, SysTenant, SysTenantVo> implements ISysTenantService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysDeptService sysDeptServic;

    @Override
    public SysTenantVo queryById(Long tenantId) {
        return getVoById(tenantId);
    }

    @Override
    public TableDataInfo<SysTenantVo> queryPageList(SysTenantQueryBo bo) {
        PagePlus<SysTenant, SysTenantVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<SysTenantVo> queryList(SysTenantQueryBo bo) {
        return listVo(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<SysTenant> buildQueryWrapper(SysTenantQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysTenant> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTenantId() != null, SysTenant::getTenantId, bo.getTenantId());
        lqw.like(StrUtil.isNotBlank(bo.getTenantName()), SysTenant::getTenantName, bo.getTenantName());
        lqw.eq(StrUtil.isNotBlank(bo.getLeaderAccount()), SysTenant::getLeaderAccount, bo.getLeaderAccount());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), SysTenant::getStatus, bo.getStatus());
        return lqw;
    }

    @Override
    public Long insertByAddBo(SysTenantAddBo bo) {
        SysTenant add = BeanUtil.toBean(bo, SysTenant.class);
//        设置父级租户ID
        add.setTenantPid(SecurityUtils.getTenantId());
        validEntityBeforeSave(add);
        boolean save = save(add);
        if (save) {
            SysDept dept = new SysDept();
            dept.setDeptName(bo.getTenantName());
            dept.setOrderNum(0);
            dept.setLeaderAccount(bo.getLeaderAccount());
            dept.setAncestors("0");
            dept.setTenantId(add.getTenantId());
            dept.setParentId(0L);
            sysDeptServic.save(dept);
        }
        return add.getTenantId();
    }

    @Override
    public Boolean updateByEditBo(SysTenantEditBo bo) {
        SysTenant update = BeanUtil.toBean(bo, SysTenant.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(SysTenant entity) {
        if (UserConstants.NOT_UNIQUE.equals(checkTenantNameUnique(entity.getTenantName(), entity.getTenantId()))) {
            throw new ServiceException(String.format("%1$s 已存在" , entity.getTenantName()));
        }
    }

    /**
     * 校验租户名称是否唯一
     *
     * @param tenantName 租户名称
     * @return 结果
     */
    @Override
    public String checkTenantNameUnique(String tenantName, Long tenantId) {
        long count = count(new LambdaQueryWrapper<SysTenant>()
            .eq(SysTenant::getTenantName, tenantName)
            .eq(SysTenant::getDelFlag, "0")
            .ne(tenantId != null, SysTenant::getTenantId, tenantId));
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    /**
     * 取消授权用户角色
     *
     * @param user 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(SysUser user) {
        SysUser entity = sysUserMapper.selectUserById(user.getUserId());
        entity.setUserType("02");
        return sysUserMapper.updateById(entity);
    }

    /**
     * 批量取消授权用户租户
     *
     * @param tenantId 租户ID
     * @param userIds  需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteAuthUsers(Long tenantId, Long[] userIds) {
        SysUser entity = new SysUser();
        entity.setUserType("02");
        return sysUserMapper.update(entity, new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getUserType, "01")
            .in(SysUser::getUserId, Arrays.asList(userIds)));
    }

    /**
     * 批量选择授权用户租户
     *
     * @param tenantId 租户ID
     * @param userIds  需要删除的用户数据ID
     * @return 结果
     */
    @Override
    public int insertAuthUsers(Long tenantId, Long[] userIds) {
        // 新增用户与租户管理
        SysUser entity = new SysUser();
        entity.setUserType("01");
        entity.setTenantId(tenantId);
        entity.setDeptId(sysDeptServic.getRootDeptByTenantId(tenantId).getDeptId());
        return sysUserMapper.update(entity, new LambdaQueryWrapper<SysUser>()
            .eq(SysUser::getUserType, "02")
            .in(SysUser::getUserId, Arrays.asList(userIds)));
    }
}
